package com.doge.calcalbum.db

import androidx.lifecycle.LiveData
import androidx.room.*
import com.doge.calcalbum.db.model.Album
import com.doge.calcalbum.db.model.AlbumCover
import com.doge.calcalbum.db.model.AlbumTitle

@Dao
interface AlbumDao {

    @Query("SELECT album.id AS id, album.coverEntryId AS coverEntryId, album.title AS title, album.createTime AS createTime, album.count AS count, album.type AS type, entry.filePath AS cover FROM album LEFT JOIN entry ON album.coverEntryId = entry.id WHERE type = :type ORDER BY createTime ASC")
    fun query(type: Int): LiveData<List<Album>>

    @Query("SELECT * FROM album WHERE id = :albumId")
    fun queryById(albumId: Int): Album?

    @Query("SELECT * FROM album WHERE id = :albumId")
    fun queryByIdLiveData(albumId: Int): LiveData<Album?>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(album: Album)

    @Update(entity = Album::class)
    fun updateTitle(album: AlbumTitle)

    @Update(entity = Album::class)
    fun updateCover(album: AlbumCover)

    @Query("UPDATE album SET count = (SELECT COUNT(id) FROM entry WHERE (albumId = :albumId AND deleteTime <= 0)) WHERE id = :albumId ")
    fun updateCount(albumId: Int)

    @Delete
    fun delete(album: Album)

    @Query("SELECT count(*) FROM entry LEFT JOIN album ON entry.albumId = album.id WHERE album.type = :type")
    fun totalCount(type: Int): Int
}